using DeviceCommons.DeviceMessages.Enums;
using DeviceCommons.DeviceMessages.Models.V1;

namespace DeviceCommons.DeviceMessages.Factories
{
    /// <summary>
    /// 可配置的状态工厂
    /// 根据设备状态配置自动创建状态
    /// </summary>
    public class ConfigurableStateFactory : IStateFactory
    {
        private readonly IDeviceStateConfiguration _configuration;

        public ConfigurableStateFactory(IDeviceStateConfiguration configuration)
        {
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
        }

        public IDeviceMessageInfoReadingState CreateState(byte sid, object value, StateValueTypeEnum? valueType = null)
        {
            // 获取状态定义
            var stateDef = _configuration.GetStateDefinition(sid);
            if (stateDef == null)
            {
                throw new ArgumentException($"未找到设备类型 {_configuration.DeviceType} 的状态ID {sid} 的定义");
            }

            // 验证状态值
            if (!_configuration.ValidateStateValue(sid, value))
            {
                throw new ArgumentException($"状态ID {sid} 的值 {value} 验证失败");
            }

            // 使用配置中定义的值类型，如果没有提供的话
            var actualValueType = valueType ?? stateDef.ValueType;

            return new DeviceMessageInfoReadingState
            {
                SID = sid,
                ValueType = actualValueType,
                ValueText = value,
                Metadata = stateDef.Name // 可选：将状态名称作为元数据
            };
        }

        public IDeviceMessageInfoReadingStates CreateStates(params StateValueTypeEnum[] types)
        {
            var states = new List<IDeviceMessageInfoReadingState>();
            
            foreach (var stateDef in _configuration.StateDefinitions)
            {
                // 使用默认值或创建空状态
                var value = stateDef.DefaultValue ?? GetDefaultValueForType(stateDef.ValueType);
                var state = CreateState(stateDef.Sid, value, stateDef.ValueType);
                states.Add(state);
            }

            return new DeviceMessageInfoReadingStates
            {
                StateArray = states.ToArray()
            };
        }

        /// <summary>
        /// 根据状态定义创建完整的状态集合
        /// </summary>
        /// <param name="values">状态值字典，键为状态ID，值为状态值</param>
        /// <returns>状态集合</returns>
        public IDeviceMessageInfoReadingStates CreateStatesFromValues(Dictionary<byte, object> values)
        {
            var states = new List<IDeviceMessageInfoReadingState>();
            
            foreach (var stateDef in _configuration.StateDefinitions)
            {
                if (values.TryGetValue(stateDef.Sid, out var value))
                {
                    // 使用提供的值
                    var state = CreateState(stateDef.Sid, value, stateDef.ValueType);
                    states.Add(state);
                }
                else if (stateDef.IsRequired)
                {
                    // 必需状态但没有提供值，使用默认值
                    var defaultValue = stateDef.DefaultValue ?? GetDefaultValueForType(stateDef.ValueType);
                    var state = CreateState(stateDef.Sid, defaultValue, stateDef.ValueType);
                    states.Add(state);
                }
                // 非必需状态且没有提供值，跳过
            }

            return new DeviceMessageInfoReadingStates
            {
                StateArray = states.ToArray()
            };
        }

        /// <summary>
        /// 根据状态定义创建完整的状态集合（使用参数数组）
        /// </summary>
        /// <param name="stateValues">状态值元组数组：(sid, value)</param>
        /// <returns>状态集合</returns>
        public IDeviceMessageInfoReadingStates CreateStatesFromValues(params (byte sid, object value)[] stateValues)
        {
            var values = stateValues.ToDictionary(sv => sv.sid, sv => sv.value);
            return CreateStatesFromValues(values);
        }

        /// <summary>
        /// 获取类型的默认值
        /// </summary>
        /// <param name="valueType">值类型</param>
        /// <returns>默认值</returns>
        private object GetDefaultValueForType(StateValueTypeEnum valueType)
        {
            return valueType switch
            {
                StateValueTypeEnum.String => string.Empty,
                StateValueTypeEnum.Int32 => 0,
                StateValueTypeEnum.Int16 => (short)0,
                StateValueTypeEnum.UInt16 => (ushort)0,
                StateValueTypeEnum.Float32 => 0.0f,
                StateValueTypeEnum.Double => 0.0,
                StateValueTypeEnum.Bool => false,
                StateValueTypeEnum.Binary => Array.Empty<byte>(),
                StateValueTypeEnum.Timestamp => 0UL,
                _ => string.Empty
            };
        }

        /// <summary>
        /// 验证提供的状态值是否完整
        /// </summary>
        /// <param name="providedSids">提供的状态ID集合</param>
        /// <returns>验证结果</returns>
        public (bool IsValid, IEnumerable<byte> MissingStates) ValidateStateCompleteness(IEnumerable<byte> providedSids)
        {
            var missingStates = _configuration.GetMissingRequiredStates(providedSids);
            var isValid = !missingStates.Any();
            return (isValid, missingStates);
        }
    }
}
